import ConfigHandler from "../init/ConfigHandler";
import tools from "../utils/DateUtils";
let local_ip =  [];
let ipnum = tools.local_ip();
Object.keys(ipnum).forEach(e=>{
    local_ip.push(ipnum[e].address+":"+ConfigHandler.getServers("port"));
})
local_ip.push("0.0.0.0:"+ConfigHandler.getServers("port"));

//解决跨域
export = cross;
async function cross(ctx:any,next:Function){
    //解决跨域问题，这样子无法携带cookiereq.headers.origin
    // 先判断是不是跨域
    let cross = ctx.req.headers.referer?.substring(0,ctx.req.headers.referer.length-1) || ctx.req.headers.host;
    // 如果为真表示是本框架自身发送的请求，就不需要进行跨域设置
    if(local_ip.includes(cross)) {return}
    ctx.res.setHeader("Access-Control-Allow-Origin", cross);
    ctx.res.setHeader("Access-Control-Allow-Credentials",true)
    ctx.res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Token, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    //设置默认类型为utf-8
    ctx.res.setHeader("Content-Type", "text/html; charset=utf-8");
    await next()
    !ctx.response.lock && ctx.res.getHeader("Set-Cookie") && ctx.res.setHeader('Set-Cookie', ctx.res.getHeader("Set-Cookie")+"Secure; SameSite=None");
}

// 初始化一下
cross.update_local_ip = ()=>{
    local_ip = [];
    let ipnum = tools.local_ip();
    Object.keys(ipnum).forEach(e=>{
        local_ip.push(ipnum[e].address+":"+ConfigHandler.getServers("port"));
    })
    local_ip.push("0.0.0.0"+":"+ConfigHandler.getServers("port"));
}